package com.example.spring.jpa.specification;

import com.example.spring.jpa.ast.PriorityOperation;

import javax.persistence.criteria.*;

/**
 * @author: orange
 * @create: 2023-07-24 20:36
 * @description:
 */
public class BooleanGenerate extends GlobalPredicate {

    @Override
    public Expression<Boolean> getExpression(GenerateApplicationContext context) {
        if (context.getPath() != null) {
            return context.getPath().as(Boolean.class);
        }
        return context.getRoot().get(context.getLeft()).as(Boolean.class);
    }

    @Override
    public Predicate doGenerate(GenerateApplicationContext context) {
        Expression<Boolean> expression = getExpression(context);
        boolean val = Boolean.parseBoolean(context.getRight());
        if (PriorityOperation.NotEquals$1.getOperation().equals(context.getOperation())
                || PriorityOperation.NotEquals$2.getOperation().equals(context.getOperation())){
            return context.getBuilder().notEqual(expression, val);
        } else if (PriorityOperation.Equals.getOperation().equals(context.getOperation())) {
            return context.getBuilder().equal(expression, val);
        }
        throw new RuntimeException(String.format("Boolean类型不支持%s运算符", context.getOperation()));
    }
}
